package com.ylsk.check.task;



import com.ylsk.check.domain.ReportInfo;
import com.ylsk.check.domain.emum.ConstructionStatusEnum;
import com.ylsk.check.domain.vo.JeevesReportVO;
import com.ylsk.check.mapper.JeevesReportMapper;
import com.ylsk.check.mapper.ReportInfoMapper;
import org.apache.commons.compress.utils.Lists;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 自定义任务
 */
@Component("customerTask")
public class CustomerTask {


    @Autowired
    private JeevesReportMapper jeevesReportMapper;

    @Autowired
    private ReportInfoMapper reportInfoMapper;

    /**
     * 更新施工状态
     */
    public void updateConstructionStatusTask(){
        //获取所有id
        List<JeevesReportVO> jeevesReportVOList = jeevesReportMapper.selectJeevesByReportInfoId();
        if(CollectionUtils.isEmpty(jeevesReportVOList)) return;

        //  按照施工报备id 进行数据分组
        Map<Long, List<JeevesReportVO>> listMap = jeevesReportVOList.stream().collect(Collectors.groupingBy(JeevesReportVO::getReportInfoId));
        List<Long> ids = Lists.newArrayList();
        for (Map.Entry<Long, List<JeevesReportVO>> vo : listMap.entrySet()) {
            Long reportInfoId = vo.getKey();
            List<JeevesReportVO> jeevesReportVOS = vo.getValue();

            Boolean changeFlag = true;
            for (JeevesReportVO jeevesReportVO : jeevesReportVOS) {
                //占道截止时间 大于当前时间
                if(new DateTime(jeevesReportVO.getJeevesEndDate()).isAfterNow()){
                    changeFlag = false;
                }
            }
            if(changeFlag){
                ids.add(reportInfoId);
            }

        }
        if(!CollectionUtils.isEmpty(ids)){
            List<ReportInfo> reportInfoList = reportInfoMapper.selectBatchIds(ids);
            for (ReportInfo reportInfo : reportInfoList) {
                reportInfo.setConstructionStatus(ConstructionStatusEnum.CONSTRUCTION.getCode());
                reportInfoMapper.updateById(reportInfo);
            }
        }
    }
}
